package com.ruoyi.yys.domain.factory;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import com.ruoyi.common.constant.ExcelStants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.yys.domain.ImportExportTemplate;
import com.ruoyi.yys.domain.export.DictVo;
import com.ruoyi.yys.util.OssUtils;
import com.ruoyi.yys.util.YamlUtil;
import com.ruoyi.yys.util.excel.ExcelUtils;
import com.ruoyi.yys.util.excel.TemplateUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * excel导出
 *
 * @author lys
 * @date 2022/12/26
 */
public class FacExcelExport implements FactoryOperaty {
    private ExcelUtils excelUtils;

    private ImportExportTemplate template;

    private List<Entity> datas;

    private String id;

    private TimeInterval timer;

    private String filePath;

    /**
     * 实例化
     *
     * @param template   模板
     * @param excelUtils excelUtils工具类
     * @param datas      数据
     * @param id         id
     * @param timer      计时器
     */
    public FacExcelExport(ImportExportTemplate template, ExcelUtils excelUtils, List<Entity> datas, String id, TimeInterval timer, String filePath) {
        this.template = template;
        this.excelUtils = excelUtils;
        this.datas = datas;
        this.id = id;
        this.timer = timer;
        this.filePath = filePath;
    }

    @Override
    public void execute() {
        String pathFile = template.getFilePath();
        if (StrUtil.isBlank(pathFile)) {
            throw new ServiceException(400, "模板路径为空");
        }
        //处理图片数据
        datas = operatImg(template, datas);
        //是excel模板的方式导出
        Integer fileType = template.getFileType();
        if (fileType == 1) {
            //本地文件路径
            TemplateUtils.generateFileByTemplateFliePath(pathFile, datas, filePath);
        } else if (fileType == 2) {
            //oss文件路径
            TemplateUtils.generateFileByTemplateOssPath(pathFile, datas, filePath);
        }
    }

    /**
     * 处理图片数据
     *
     * @param template 模板
     * @param datas    数据
     * @return {@link List}<{@link Entity}>
     */
    public static List<Entity> operatImg(ImportExportTemplate template, List<Entity> datas) {
        DictVo dictData = YamlUtil.strToDictVo(template.getDict());
        if (ObjectUtil.isEmpty(dictData)) {
            return datas;
        }
        Map<String, Integer> img = dictData.getImg();
        if (MapUtil.isEmpty(img)) {
            return datas;
        }
        //图片key
        Set<String> imgKeys = img.keySet();
        Set<String> dataKeys = datas.get(0).keySet();
        //找到交集，以免参数imgKeys在dataKey里面不存在
        Collection<String> keys = CollUtil.intersection(imgKeys, dataKeys);
        if (IterUtil.isEmpty(keys)) {
            return datas;
        }
        return datas.stream().peek(e -> {
            for (String key : keys) {
                //图片列跨
                Integer colSpan = img.get(key);
                if (ObjectUtil.isEmpty(colSpan)) {
                    //默认为1列
                    colSpan = 1;
                }
                try {
                    //图片地址
                    String imgPath = e.getStr(key);
                    //获取oss图片byte数据
                    byte[] imgByte = OssUtils.getPicByte(imgPath, ExcelStants.IMG_YS);
                    ImageEntity imageEntity = new ImageEntity();
                    imageEntity.setData(imgByte);
                    //设置列跨度
                    imageEntity.setColspan(colSpan);
                    e.set(key, imageEntity);
                } catch (Exception x) {
                    //表示图片数据获取失败
                }
            }
        }).collect(Collectors.toList());
    }
}
